import React from 'react';
import classNames from 'classnames';
import request from '@/utils/request';
import { message } from 'antd';
import styles from './index.less';

import exportExcel from './exportExcel';

interface AfterRequestFunc {
  (response: { data?: [] | {} }): [];
}

interface ExportFormProps {
  action: string;
  columns: string[];
  afterRequest: AfterRequestFunc;
  className?: string;
  count?: number;
  data?: {};
  method?: string;
}

const ExportFormData: React.FC<ExportFormProps> = (props) => {
  const {
    action,
    data = {},
    method = 'POST',
    className,
    count,
    columns = [],
    afterRequest,
  } = props;

  const clickHandle = async () => {
    let response;
    if (method === 'POST') {
      response = await request(action, {
        method,
        data,
      });
    } else {
      response = await request(action, {
        method,
        params: data,
      });
    }

    if (response.code) {
      message.error('导出失败');
      return;
    }

    let list: object[] = [];
    if (typeof afterRequest === 'function') {
      list = afterRequest(response);
    }

    exportExcel({
      dataTitle: columns,
      dataSource: list,
    });
  };

  return (
    <div className={classNames(styles['export-view'], className)}>
      <div>{count && count !== 0 ? `共找到 ${count} 条内容` : ''}</div>
      <div className={styles['export-box']} onClick={clickHandle}>
        导出Excel
      </div>
    </div>
  );
};

export default ExportFormData;
